package com.kai.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.kai.pojo.User;
import com.kai.service.UserService;
import com.kai.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
@Slf4j
public class UploadController {
    @Autowired
    private UserService userService;

    @PostMapping("/uploadImg")
    @ResponseBody
    public String uploadImg(@RequestPart("file") MultipartFile file, HttpServletRequest request){
        String s = file.getOriginalFilename();
        String name= UUIDUtils.getUUID() +s.substring(s.lastIndexOf("."));
        try {
            file.transferTo(new File(request.getSession().getServletContext().getRealPath("/upload/")+name));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return request.getScheme()+"://"+request.getServerName()+":"+request.getLocalPort()+request.getContextPath()+"/upload/"+name;
    }

    /**
     * 导出execl
     * @param response
     */
    @GetMapping("/execl")
    @ResponseBody
    public void execl(HttpServletResponse response){
        List<User> list = userService.selectAllUserExecl();
        try {
            response.setContentType("application/vnd.ms-excel; charset=utf-8");
            response.setCharacterEncoding("utf-8");
            String fileName = "用户信息";
            response.setHeader("Content-Disposition", "attachment;filename=" + "导出记录"+ ".xlsx");
            log.info(URLEncoder.encode(fileName, "utf-8") + ".xlsx");
            EasyExcel.write(response.getOutputStream(), User.class).sheet("用户信息").doWrite(list);
        } catch (Exception e) {
            log.error("下载报表异常：{}", e.getMessage());
            throw new RuntimeException("下载报表异常");
        }
    }
}
